package com.tx.studentManager.utils;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Date;

import org.apache.log4j.Logger;

import com.tx.studentManager.model.User;

public class ReflectUtils {
	private static Logger logger=Logger.getLogger(ReflectionUtils.class);
	
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static <T> Class<T> getClassGenricType(final Class clazz) {
         
        return (Class<T>)((ParameterizedType)clazz.getGenericSuperclass()).getActualTypeArguments()[0];
    }
    
    /**
     * 
    * 将一个对象中不为空的字段拷贝到另一个对象
    * @param from
    * @param to
     */
    public static void copyFields(Object from,Object to){
    	if (from.getClass()!=to.getClass()) {
			logger.info("拷贝两对象类型不同，不允许拷贝");
		}
    	Field[] fromFields=from.getClass().getDeclaredFields();
    	Field[] toFields=to.getClass().getDeclaredFields();
    	for (int i = 0; i < fromFields.length; i++) {
    		if (fromFields[i].getModifiers()>16) {
    			//跳过静态变量
				continue;
			}
			try {
				fromFields[i].setAccessible(true);
				Object value=fromFields[i].get(from);
				if (value!=null) {
					toFields[i].setAccessible(true);
					toFields[i].set(to, value);
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
    }
    public static void main(String[] args) {
		User from=new User();
		from.setAge(15);
		from.setUserId(32);
		from.setEmail("e4jkfdsapg");
		from.setCreateDate(new Date());
		User to=new User();
		to.setAge(100);
		ReflectUtils.copyFields(from, to);
		System.out.println(to.getAge());
	}
}
